<template>
  <div class="circuit-viewer-container">
    <iframe
        ref="circuitIframe"
        :src="iframeUrl"
        frameborder="0"
        class="circuit-iframe"
        @load="onIframeLoad"
    ></iframe>
  </div>
</template>

<script>
export default {
  props: {
    circuitData: {
      type: Object,
      default: null
    },
    scale: {
      type: Number,
      default: 1.0
    }
  },
  data() {
    return {
      iframeUrl: '',
      iframeReady: false
    }
  },
  watch: {
    circuitData: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.generateIframeUrl(newVal)
        }
      }
    }
  },
  methods: {
    generateIframeUrl(data) {
      // 生成iframe要加载的URL
      // 这里假设有一个circuit-viewer.html页面可以处理电路图数据
      const jsonStr = encodeURIComponent(JSON.stringify(data))
      this.iframeUrl = `/circuit-viewer.html?data=${jsonStr}`
    },
    onIframeLoad() {
      this.iframeReady = true
      this.setScale(this.scale)
    },
    setScale(scale) {
      if (this.iframeReady && this.$refs.circuitIframe) {
        try {
          const iframe = this.$refs.circuitIframe
          iframe.contentWindow.postMessage({
            type: 'setScale',
            scale: scale
          }, '*')
        } catch (error) {
          console.error('设置缩放比例失败:', error)
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.circuit-viewer-container {
  height: 100%;
  width: 100%;

  .circuit-iframe {
    width: 100%;
    height: 100%;
    background-color: #fff;
  }
}
</style>